<template>
  <el-dialog v-bind="{ ...$attrs }" class="app-add" >
      <el-tabs type="card">
        <el-tab-pane label="修改用户">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"  status-icon>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email" />
            </el-form-item>
            <!-- <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password" show-password />
            </el-form-item> -->
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
          <el-button  @click="$emit('close')"> 关闭 </el-button>
          <el-button  type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
      </template>
  </el-dialog>
</template>
 
<script lang="ts" setup>
import { reactive, ref ,withDefaults,defineEmits,watch} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getUser,editUser } from '@/server/user'
import { ElMessage } from 'element-plus'
//定义自定义事件
const emit = defineEmits<{(event: 'close'): void;(event: 'success'): void;  }>()
const props = withDefaults(defineProps<Props>(), {
	id:''
})
//定义属性
interface RuleForm {
  userName: string,
  email: string
}
//表单
const formSize = ref('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userName: '',
  email: ''
})

const rules = reactive<FormRules<RuleForm>>({
    userName:[{
      required:true,
      message:"请输入用户名"
    }],
    email:[{
      required:true,
      message:"请输入邮箱"
    }]
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate( async (valid, fields) => {
    if (valid) {
      console.log('submit!')
      try{
        await editUser(props.id,ruleForm)
        ElMessage.success("修改成功")
        emit("success")
        
      }catch(err){
        ElMessage.error("修改失败")
      }
      
    } else {
      console.log('error submit!', fields)
    }
  })
}
interface Props {
	id: string;
}

//获取用户
const getUserData=async (id:string)=>{
   const data= await getUser(id)
   ruleForm.userName=data.userName
   ruleForm.email=data.email
  //  ruleForm.password=data.password
}
getUserData(props.id)

watch(  
  () => props.id,  
  (newText, oldText) => {  
    console.log('Text changed from', oldText, 'to', newText);  
  },  
  { immediate: true } // 立即执行回调一次，以处理初始值  
);  
</script>
<style lang="scss" scoped>
 .el-dialog{
  height: 500px !important;
  overflow: auto;
  // .el-tabs{
  //   height: 400px;
  //   overflow: auto;
  // }
}
</style>